package com.wms.web.controller.base;

import com.wms.base.domain.BaseLocation;
import com.wms.base.domain.BaseMat;
import com.wms.base.mapper.BaseMatMapper;
import com.wms.base.service.BaseLocationService;
import com.wms.base.service.BaseMatService;
import com.wms.base.service.BaseWarehouseService;
import com.wms.common.annotation.Log;
import com.wms.common.bean.LocationPdfData;
import com.wms.common.bean.MatLabelPdfData;
import com.wms.common.bean.request.MatLabelRequestData;
import com.wms.common.bean.request.PutOnRequestBody;
import com.wms.common.core.controller.BaseController;
import com.wms.common.core.domain.AjaxResult;
import com.wms.common.core.page.TableDataInfo;
import com.wms.common.enums.BusinessType;
import com.wms.stock.PDFService;
import com.wms.common.utils.bean.BeanUtils;
import com.wms.common.utils.poi.ExcelUtils;
import com.wms.stock.domain.StockMatLabel;
import com.wms.stock.service.StockMatLabelService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 货位Controller
 */
@RestController
@RequestMapping("/base/location")
public class BaseLocationController extends BaseController {
    @Autowired
    private BaseLocationService baseLocationService;
    @Autowired
    private BaseWarehouseService baseWarehouseService;
    @Autowired
    private StockMatLabelService stockMatLabelService;
    @Autowired
    private PDFService pdfService;

    /**
     * 查询货位列表
     *
     * @param baseLocation
     * @return
     */
    @PreAuthorize("@ss.hasPermi('base:location:list')")
    @GetMapping("/list")
    public TableDataInfo list(BaseLocation baseLocation) {
        startPage();
        List<BaseLocation> list = baseLocationService.selectBaseLocationList(baseLocation);
        if (CollectionUtils.isNotEmpty(list)) {
            for (BaseLocation location : list) {
                location.setWarehouseName(baseWarehouseService.selectBaseWarehouseNameByWarehouseCode(location.getWarehouseCode()));
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出货位列表
     *
     * @param response
     * @param baseLocation
     */
    @PreAuthorize("@ss.hasPermi('base:location:export')")
    @Log(title = "货位", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BaseLocation baseLocation) {
        List<BaseLocation> list = baseLocationService.selectBaseLocationList(baseLocation);
        ExcelUtils<BaseLocation> util = new ExcelUtils<>(BaseLocation.class);
        util.exportExcel(response, list, "货位数据");
    }

    /**
     * 获取货位详细信息
     *
     * @param locationId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('base:location:query')")
    @GetMapping(value = "/{locationId}")
    public AjaxResult getInfo(@PathVariable("locationId") Long locationId) {
        return AjaxResult.success(baseLocationService.selectBaseLocationByLocationId(locationId));
    }

    /**
     * 新增货位
     *
     * @param baseLocation
     * @return
     */
    @PreAuthorize("@ss.hasPermi('base:location:add')")
    @Log(title = "货位", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BaseLocation baseLocation) {
        baseLocation.setCreateBy(getUsername());
        return toAjax(baseLocationService.insertBaseLocation(baseLocation));
    }

    /**
     * 修改货位
     *
     * @param baseLocation
     * @return
     */
    @PreAuthorize("@ss.hasPermi('base:location:edit')")
    @Log(title = "货位", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BaseLocation baseLocation) {
        baseLocation.setUpdateBy(getUsername());
        return toAjax(baseLocationService.updateBaseLocation(baseLocation));
    }

    /**
     * 删除货位
     *
     * @param locationIds
     * @return
     */
    @PreAuthorize("@ss.hasPermi('base:location:remove')")
    @Log(title = "货位", businessType = BusinessType.DELETE)
    @DeleteMapping("/{locationIds}")
    public AjaxResult remove(@PathVariable Long[] locationIds) {
        return toAjax(baseLocationService.deleteBaseLocationByLocationIds(locationIds));
    }

    /**
     * 打印货位
     *
     * @param response
     * @param locationId
     * @throws Exception
     */
    @GetMapping("printLocation/{locationId}")
    public void printLocation(HttpServletResponse response, @PathVariable Long locationId) throws Exception {
        OutputStream out = response.getOutputStream();
        BaseLocation location = baseLocationService.selectBaseLocationByLocationId(locationId);
        StockMatLabel baseMat = stockMatLabelService.selectStockMatLabelByMatCode(location.getLocationCode());
        PutOnRequestBody p = new PutOnRequestBody();
        p.setWarehouseCode(location.getWarehouseCode());
        p.setLocationCode(location.getLocationCode());
        List<MatLabelRequestData> matLabelList = new ArrayList<>();
        if (baseMat != null) {
            MatLabelRequestData m = new MatLabelRequestData();
            m.setMatCode(baseMat.getMatCode());
            m.setMatName(baseMat.getMatName());
            m.setUsableQuantity(baseMat.getUsableQuantity());
            m.setReceivedQuantity(baseMat.getReceivedQuantity());
            matLabelList.add(m);
        }
        p.setMatLabelList(matLabelList);
        if (p != null) {
            LocationPdfData locationPdfData = new LocationPdfData();
            locationPdfData.setLocationCode(p.getLocationCode());
            locationPdfData.setWarehouseCode(p.getWarehouseCode());
            locationPdfData.setMatCode(String.valueOf(p.getMatLabelList().get(0).getMatCode()));
//            BeanUtils.copyBeanProp(locationPdfData, p);
            InputStream in = new FileInputStream(new File(pdfService.printLocation(locationPdfData)));
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            response.setContentType("application/pdf");
            in.close();
        }
    }
}
